const path = require('path');
const express = require('express');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

const port = 3000 ;
const app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

/* - - - - 启用解析cookie的中间件 - - - - - - - - -  */
app.use( cookieParser() );

app.get( '/' , (req,resp)=>{
  resp.redirect( '/index.html' );
});

app.get( '/cookie/produce' , (req,resp)=>{

  let cookieOptions = {
    // 设置 cookie 的最大存活时间
    maxAge: 1000 * 60 * 60 * 24 * 7,
    // 设置脚本是否可访问 
    // httpOnly 为 true 表示在浏览器端不能通过脚本来访问
    // httpOnly 为 true 时仅在 http 或 https 请求和响应 中使用 cookie
    httpOnly: false ,
    // 设置是否仅在安全链接时才收发 cookie
    // secure 为 true 时表示只有在 https 请求时才收发 cookie
    secure: false ,
    path: '/cookie' 
  }
  resp.cookie( 'KAIFAMIAOID' , '666888999777' , cookieOptions );
  resp.cookie( 'WANGAYI' , 'LAOWANGAYIHAOKUN' , cookieOptions );

  console.log( resp.header( 'set-cookie' ) );

  let entity = `<div>
                  生成成功，请在浏览器中查看( chrome://settings/siteData )
                </div>
                <script src="/cookie-operate.js" type="text/javascript"></script>`
  resp.send( entity );
});

app.get( '/student/receive' , (req,resp)=>{
  console.log( 'cookie: ' , req.header( 'cookie' ) );
  let cookies = req.cookies ;
  console.log( 'cookies: ' , cookies );
  resp.send( '<p>hello</p>' );
});

app.get( '/cookie/receive' , (req,resp)=>{
  console.log( 'cookie: ' , req.header( 'cookie' ) );
  let cookies = req.cookies ;
  console.log( 'cookies: ' , cookies );
  resp.send( '<p>hello</p>' );
});


app.listen( port );